//
//  LXLineChartView.m
//  bgms_d
//
//  Created by lachesis-zhu on 03/07/2017.
//  Copyright © 2017 lachesis-zhu. All rights reserved.
//

#import "LXLineChartView.h"
#import "UIImage+Common.h"
#import "UIButton+EnlargeTouchArea.h"
#import "UIView+Common.h"
#import "UIColor+expanded.h"
#import "UIView+DrawSomething.h"

#import "LXSLineRecord.h"
#import "LXDevSettingModel.h"

#define btnW 6
#define textW 30
#define titleWOfY 50
#define titleWOfX 32
#define bottomOfX 25
#define minY 0
#define maxY 300

@interface LXLineChartView () <UIScrollViewDelegate>
{
    CGFloat currentPage;//当前页数
    CGFloat Xmargin;//X轴方向的偏移
    CGFloat Ymargin;//Y轴方向的偏移
    CGPoint lastPoint;//最后一个坐标点
    UIButton *firstBtn;
    UIButton *lastBtn;
    CGFloat _axisToViewPadding;
    CAShapeLayer *_bezierLineLayer;
    CGPoint firstPoint;
    UIBezierPath *beizer;
    CAShapeLayer *shapeLayer;
}

@property (nonatomic, strong) UIScrollView *chartScrollView;
@property (nonatomic, strong) UIView *bgView1;//背景图
@property (nonatomic, strong) UIPageControl *pageControl;//分页
@property (nonatomic, strong) UIView *scrollBgView1;
@property (nonatomic, strong) NSMutableArray *leftPointArr;//左边的数据源
@property (nonatomic, strong) NSMutableArray *leftBtnArr;//左边按钮
@property (nonatomic, strong) NSMutableArray *detailLabelArr;
@property (nonatomic, strong) NSMutableArray *leftScaleArr;
@property (nonatomic, strong) NSMutableArray *leftScaleViewArr;//左边的点击显示图
@property (nonatomic, strong) UIView *scaleBgView;
@property (nonatomic, strong) UILabel *lineLabel;
@property (nonatomic, strong) UILabel *scaleLabel;
@property (nonatomic, strong) UILabel *dateTimeLabel;
@property (nonatomic, assign) NSDate *starDrawtDate;
@property (nonatomic, strong) NSMutableArray *redrwaData;

@end

@implementation LXLineChartView

- (UILabel *)scaleLabel {
    if (!_scaleLabel) {
        _scaleLabel = [[UILabel alloc] init];
        _scaleLabel.textAlignment = 1;
        _scaleLabel.text = @"3.3681%";
        _scaleLabel.font = [UIFont lx_systemFontOfSize:11];
        _scaleLabel.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:159 / 255.0 blue:106 / 255.0 alpha:1];
        _scaleLabel.textColor = [UIColor whiteColor];
    }
    return _scaleLabel;
}

- (UILabel *)dateTimeLabel {
    if (!_dateTimeLabel) {
        _dateTimeLabel = [[UILabel alloc] init];
        _dateTimeLabel.textAlignment = 1;
        _dateTimeLabel.text = @"2016.04.16";
        _dateTimeLabel.font = [UIFont lx_systemFontOfSize:11];
        _dateTimeLabel.backgroundColor = [UIColor whiteColor];
        _dateTimeLabel.textColor = [UIColor colorWithRed:181 / 255.0 green:181 / 255.0 blue:181 / 255.0 alpha:1];
    }
    return _dateTimeLabel;
}

- (UILabel *)lineLabel {
    
    if (!_lineLabel) {
        _lineLabel = [[UILabel alloc] init];
        _lineLabel.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:159 / 255.0 blue:106 / 255.0 alpha:1];
    }
    return _lineLabel;
}

/**  背景 */
- (UIView *)scrollBgView1 {
    if (!_scrollBgView1) {
        _scrollBgView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.chartScrollView.contentSize.width, self.chartScrollView.bounds.size.height)];
    }
    return _scrollBgView1;
}

/**  背景网格 */
- (UIView *)bgView1 {
    if (!_bgView1) {
        _bgView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.chartScrollView.contentSize.width, self.chartScrollView.bounds.size.height - bottomOfX)];
        _bgView1.layer.masksToBounds = YES;
        //        _bgView1.layer.cornerRadius = 5;
        _bgView1.layer.borderWidth = 1;
        _bgView1.layer.borderColor = kAppLinesColor.CGColor;
    }
    return _bgView1;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        currentPage = 0;
        _axisToViewPadding = 30;
        self.leftPointArr = [NSMutableArray array];
        self.leftBtnArr = [NSMutableArray array];
        self.detailLabelArr = [NSMutableArray array];
        self.leftScaleArr = [NSMutableArray array];
        self.leftScaleViewArr = [NSMutableArray array];
        [self addDetailViews];
    }
    return self;
}

- (void)layoutSubviews
{
    NSLog(@"is in layoutSubviews");
}

- (void)initStartDatas
{
    currentPage = 0;
    self.leftPointArr = [NSMutableArray array];
    self.leftBtnArr = [NSMutableArray array];
    self.detailLabelArr = [NSMutableArray array];
    self.leftScaleArr = [NSMutableArray array];
    self.leftScaleViewArr = [NSMutableArray array];
}

- (void)drawRect:(CGRect)rect
{
    
}

- (void)beginDrawView:(NSString *)drawData
{
    [self addDataPointWith:self.scrollBgView1 andArr:drawData withIndex:self.redrwaData.count + 1];//添加点
    [self.redrwaData addObject:drawData];
}
//*******************数据源************************//

- (void)setDataArrOfX:(NSArray *)dataArrOfX {
    _dataArrOfX = dataArrOfX;
    [dataArrOfX enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel *label = [self.scrollBgView1 viewWithTag:100 + idx];
        if (label) {
            label.text = obj;
        }
    }];
}

- (void)setDataArrOfY:(NSArray *)dataArrOfY {
    _dataArrOfY = dataArrOfY;
}

- (void)setLeftDataArr:(NSArray *)leftDataArr {
    _leftDataArr = leftDataArr;
}

//*******************分割线************************//
- (void)addDetailViews {

    self.chartScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(titleWOfX, titleWOfY, kScreenWidth - titleWOfX, self.bounds.size.height - titleWOfY)];
    self.chartScrollView.contentOffset = CGPointMake(0, 0);
    self.chartScrollView.backgroundColor = [UIColor clearColor];
    self.chartScrollView.delegate = self;
    self.chartScrollView.showsHorizontalScrollIndicator = NO;
    self.chartScrollView.pagingEnabled = NO;
    self.chartScrollView.bounces = NO;
    self.chartScrollView.contentSize = CGSizeMake(self.chartScrollView.bounds.size.width / 7 * self.dataArrOfX.count, 0);
    self.chartScrollView.scrollEnabled = YES;
    
    [self addSubview:self.chartScrollView];
    [self addSubview:self.pageControl];
    [self.chartScrollView addSubview:self.scrollBgView1];
    [self.scrollBgView1 addSubview:self.bgView1];
}

- (void)readyBeizer {
    beizer = [UIBezierPath bezierPath];
    shapeLayer = [CAShapeLayer layer];
    shapeLayer.lineWidth = 1;
    shapeLayer.fillColor = [UIColor redColor].CGColor;
    shapeLayer.strokeColor = [UIColor blackColor].CGColor;
    shapeLayer.lineCap = kCALineCapRound;
    [self.scrollBgView1.layer addSublayer:shapeLayer];
}

//添加左边的坐标线
- (void)addLeftBezierPoint:(UIButton *)drawButton {
    CGPoint drawPoint = drawButton.center;
    NSValue *pointValue = [NSValue valueWithCGPoint:firstPoint];
    if ([pointValue isEqualToValue:[NSValue valueWithCGPoint:CGPointMake(0, 0)]]) {
        firstPoint = drawPoint;
    }
    [beizer moveToPoint:firstPoint];
    [beizer addLineToPoint:drawPoint];
    shapeLayer.path = beizer.CGPath;
    firstPoint = drawPoint;
}

- (void)drawXandY
{
    [self initStartDatas];
    [self addDetailViews];
    self.pageControl.numberOfPages = 1;
    [self addLines1With:self.bgView1];
    [self addLeftViews];
    [self addBottomViewsWith:self.scrollBgView1];
    [self readyBeizer];
    //[self reDrawView:self.redrwaData];
}

- (BOOL)reDrawView:(NSArray *)array
{
    [beizer removeAllPoints];
    [shapeLayer removeFromSuperlayer];
    [self readyBeizer];
    [self.leftScaleArr removeAllObjects];
    [self.leftBtnArr removeAllObjects];
    [self.leftPointArr removeAllObjects];
    self.redrwaData = nil;
    firstPoint = CGPointZero;
    self.redrwaData = [NSMutableArray arrayWithArray:array];
    if (self.starDrawtDate == nil) {
        NSString *startString = [self.dataArrOfX firstObject];
        NSDateFormatter *formate = [[NSDateFormatter alloc] init];
        [formate setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *dateString = [formate stringFromDate:[NSDate new]];
        NSDate *startDate = [formate dateFromString:[NSString stringWithFormat:@"%@ %@", [dateString substringToIndex:10], startString]];
        self.starDrawtDate = startDate;
    }

    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *item = obj;
        [self addDataPointWith:self.scrollBgView1 andArr:item withIndex:idx];
    }];
    return YES;
}

- (void)addDataPointWith:(UIView *)view andArr:(NSString *)drawData withIndex:(NSInteger)index {
    [self.leftScaleArr addObject:drawData];
    CGFloat height = self.chartScrollView.bounds.size.height - bottomOfX;
    CGFloat marginWidth = self.chartScrollView.bounds.size.width / 7;
    Xmargin = marginWidth;
    //初始点
    
    CGFloat maxYValue = [[self.dataArrOfY firstObject] floatValue] - [[self.dataArrOfY lastObject] floatValue];
    NSString *tempRecord = [[LXDevSettingModel shareSettingModel] tempCTempF:drawData];
    float tempHeight = [tempRecord floatValue];
    if (tempHeight == 0) {
        firstPoint = CGPointZero;
        return;
    }
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0.95 * index * Xmargin / 60 - btnW / 2, height - height * (tempHeight / maxYValue) - btnW / 2, btnW, btnW)];
    btn.layer.borderColor = [UIColor clearColor].CGColor;
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = btnW / 2;
    btn.layer.masksToBounds = YES;
    btn.tag = self.leftScaleArr.count;
    btn.hidden = NO;
    [btn addTarget:self action:@selector(TopBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setEnlargeEdgeWithTop:5 right:5 bottom:5 left:5];
    [self.scrollBgView1 addSubview:btn];
    
    NSValue *point = [NSValue valueWithCGPoint:btn.center];
    [self.leftPointArr addObject:point];
    [self.leftBtnArr addObject:btn];
    
    [self addLeftBezierPoint:btn];//添加连线
}

- (void)addLeftViews {
    
    NSArray *leftArr = _dataArrOfY;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0 + titleWOfX, 25, 2, CGRectGetMaxY(self.chartScrollView.frame) - 22)];
    lineView.backgroundColor = kAppNormalTextColor;
    [self addSubview:lineView];
    for (int i = 0; i < _dataArrOfY.count; i++ ) {
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, i * (Ymargin) - 16 / 2 + titleWOfY, titleWOfX - 5, 16)];
        leftLabel.font = [UIFont lx_systemFontOfSize:10.0f];
        leftLabel.textColor = kAppNormalTextColor;
        leftLabel.textAlignment = NSTextAlignmentRight;
        leftLabel.text = leftArr[i];
        [self addSubview:leftLabel];
        
        UIView *valueView = [[UIView alloc] initWithFrame:CGRectMake(0 + titleWOfX, i * Ymargin + titleWOfY, 6, 2)];
        valueView.backgroundColor = kAppNormalTextColor;
        [self addSubview:valueView];
    }
    
    _titleOfY = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 200, 20)];
    _titleOfY.font = [UIFont lx_systemFontOfSize:17.0f];
    _titleOfY.textAlignment = kCTTextAlignmentLeft;
    _titleOfY.textColor = kAppNormalTextColor;
    _titleOfY.text = _titleOfYStr;
    [self addSubview:self.titleOfY];
    
    UILabel *unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 2 * Xmargin - 5, 5, Xmargin * 2, 20)];
    unitLabel.font = [UIFont lx_systemFontOfSize:12.0f];
    unitLabel.textAlignment = NSTextAlignmentRight;
    unitLabel.textColor = kAppGreenTextColor;
    unitLabel.text = [NSString stringWithFormat:@"Unit(%@)", [LXDevSettingModel shareSettingModel].tempUnitF ? @"F" : @"°C"];
    [self addSubview:unitLabel];
}


- (void)addBottomViewsWith:(UIView *)showView {
    NSArray *bottomArr;
    if (showView == self.scrollBgView1) {
        bottomArr = _dataArrOfX;
    } else {

    }
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(Xmargin / 2, (self.dataArrOfY.count - 1) * Ymargin + titleWOfY, kScreenWidth, 2)];
    lineView.backgroundColor = kAppNormalTextColor;
    [self addSubview:lineView];
    
    for (int i = 0; i < bottomArr.count; i++) {
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * Xmargin - Xmargin / 2, (self.dataArrOfY.count - 1) * Ymargin, Xmargin, bottomOfX)];
        leftLabel.font = [UIFont lx_systemFontOfSize:10.0f];
        leftLabel.textColor = kAppNormalTextColor;
        leftLabel.text = bottomArr[i];
        leftLabel.tag = 100 + i;
        leftLabel.textAlignment = NSTextAlignmentCenter;
        [showView addSubview:leftLabel];
        if (i == 0) {
            leftLabel.frame = CGRectMake(leftLabel.lx_x + 15, leftLabel.lx_y, leftLabel.lx_width, leftLabel.lx_height);
        }
        UIView *valueView = [[UIView alloc] initWithFrame:CGRectMake(Xmargin + i * Xmargin, (self.dataArrOfY.count - 1) * Ymargin - 6, 2, 6)];
        valueView.backgroundColor = kAppNormalTextColor;
        [showView addSubview:valueView];
    }
    
    _titleOfX = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.scrollBgView1.frame), CGRectGetMaxY(self.chartScrollView.frame) - 22, 30, 20)];
    _titleOfX.font = [UIFont lx_systemFontOfSize:10.0f];
    _titleOfX.textAlignment = kCTTextAlignmentCenter;
    _titleOfX.textColor = kAppNormalTextColor;
    _titleOfX.text = _titleOfXStr;
    [self addSubview:self.titleOfX];
}

- (void)TopBtnAction:(UIButton *)sender {
    
    for (UIButton *btn in _leftBtnArr) {
        if (sender.tag == btn.tag) {
            btn.selected = YES;
        } else {
            btn.selected = NO;
        }
    }
    [self showDetailLabel:sender];
}

- (void)showDetailLabel:(UIButton *)sender {
    
    for (UILabel * label in _detailLabelArr) {
        if (sender.tag + 200 == label.tag) {
            label.hidden = NO;
        } else {
            label.hidden = YES;
        }
    }
}

- (void)addLines1With:(UIView *)view {
    
    CGFloat magrginHeight = (self.chartScrollView.bounds.size.height - bottomOfX) / (self.dataArrOfY.count - 1);
    CGFloat labelWith = self.chartScrollView.contentSize.width;
    Ymargin = magrginHeight;
    for (int i = 0; i < 4; i ++) {
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, magrginHeight + magrginHeight * i, labelWith, 1)];
        [lineImage drawDashLineWithLength:3 lineSpacing:2 lineColor:kAppLinesColor directionType:MTRDrawSomeHorizontal];
        [view addSubview:lineImage];
    }
    
    CGFloat marginWidth = self.chartScrollView.bounds.size.width / (self.dataArrOfX.count);
    Xmargin = marginWidth;

    CGFloat labelHeight = self.chartScrollView.bounds.size.height;
    
    for (int i = 0; i < _dataArrOfX.count; i++) {
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(marginWidth * i, 0, 1, labelHeight)];
        [lineImage drawDashLineWithLength:3 lineSpacing:2 lineColor:kAppLinesColor directionType:MTRDrawSomeVertical];
        if (i != 0) {
            [view addSubview:lineImage];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    currentPage = scrollView.contentOffset.x / self.chartScrollView.bounds.size.width;
    self.pageControl.currentPage = currentPage;
}

@end
